import React, { useState, useEffect } from "react";

const WxParseImg = ({ node }) => {
  const [newStyleStr, setNewStyleStr] = useState("");
  const [preview, setPreview] = useState(true);

  const wxParseImgTap = (e) => {
    if (!preview) return;
    const { src } = e.currentTarget.dataset;
    if (!src) return;

    let parent = findParentWithPreviewMethod();

    if (parent) {
      parent.preview(src, e);
    }
  };

  const wxParseImgLoad = (e) => {
    const { src } = e.currentTarget.dataset;
    if (!src) return;
    const { width, height } = e.nativeEvent.target;
    const recal = wxAutoImageCal(width, height);
    const { imageheight, imageWidth } = recal;
    const { padding, mode } = node.attr;
    const { styleStr } = node;
    const imageHeightStyle =
      mode === "widthFix" ? "" : `height: ${imageheight}px;`;
    setNewStyleStr(
      `${styleStr}; ${imageHeightStyle}; width: ${imageWidth}px; padding: 0 ${+padding}px;`
    );
  };

  const wxAutoImageCal = (originalWidth, originalHeight) => {
    const { padding } = node.attr;
    const windowWidth = window.innerWidth - 2 * padding;
    const results: any = {};

    if (originalWidth < 60 || originalHeight < 60) {
      const { src } = node.attr;
      let parent = findParentWithPreviewMethod();
      if (parent) {
        parent.removeImageUrl(src);
        setPreview(false);
      }
    }

    if (originalWidth > windowWidth) {
      results.imageWidth = windowWidth;
      results.imageheight = windowWidth * (originalHeight / originalWidth);
    } else {
      results.imageWidth = originalWidth;
      results.imageheight = originalHeight;
    }

    return results;
  };

  const findParentWithPreviewMethod = () => {
    let parent = node;
    while (
      parent &&
      (!parent.preview || typeof parent.preview !== "function")
    ) {
      parent = parent.parent;
    }
    return parent;
  };

  useEffect(() => {
    const handleResize = () => {
      // Handle resize logic if needed
    };

    window.addEventListener("resize", handleResize);

    return () => {
      window.removeEventListener("resize", handleResize);
    };
  }, []);

  return (
    <img
      mode={node.attr.mode}
      lazy-load={node.attr.lazyLoad}
      className={node.classStr}
      style={newStyleStr || node.styleStr}
      data-src={node.attr.src}
      src={node.attr.src}
      onClick={wxParseImgTap}
      onLoad={wxParseImgLoad}
    />
  );
};

export default WxParseImg;
